package wht.jly.forum.controller.user;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import wht.jly.forum.config.sysconstants.SystemConstants;
import wht.jly.forum.domain.User;
import wht.jly.forum.service.UserService;
import wht.jly.forum.utils.JsonData;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author lanyangji
 * @date 2019/3/2 15:15
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SystemConstants systemConstants;

    @PostMapping("/reg")
    @ResponseBody
    public JsonData post(@Valid @RequestBody User user, BindingResult result) {
        // 参数校验
        if (result.hasErrors()) {
            List<String> errors = new ArrayList<>(result.getAllErrors().size());
            result.getAllErrors().stream().forEach(
                    error -> errors.add(error.getDefaultMessage())
            );

            /**
             * 400 bad request
             */
            return JsonData.build(400, "请求参数异常", errors);
        }
        // 密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword())).setCreateTime(new Date());
         User dbUser = userService.save(user);
        return JsonData.buildSuccess("注册成功", user);
    }

    @GetMapping
    @ResponseBody
    public JsonData get(String username) {
        System.out.println(username);
        User dbUser = userService.findByUsername(username);
        if (dbUser != null) {
            return JsonData.build(400, "用户名被占用", null);
        }

        return JsonData.buildSuccess("用户名可以放心使用", null);
    }

    /**
     * 去登录页
     *
     * @return
     */
    @GetMapping("/login")
    public String login(Map<String, Object> map) {
        map.put("applicationDisplayName", systemConstants.getApplicationDisplayName());

        return "login";
    }

    @GetMapping("/reg")
    public String reg() {
        return "register";
    }
}
